package com.virgo.common.utils;

import lombok.experimental.UtilityClass;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@UtilityClass
public class IAesUtils {

	/**
	 * AES-128-CBC 加密
	 * @param content 加密的原始字符串
	 * @param IV 偏移向量IV
	 * @param KEY key
	 * @return 加密完的字符串
	 * @throws Exception 异常
	 */
	public String encrypt(String content, String IV, String KEY) throws Exception {
		byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
		//使用CBC模式，需要一个向量iv，可增加加密算法的强度
		IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
		byte[] encrypted = cipher.doFinal(content.getBytes());
		return Base64.getEncoder().encodeToString(encrypted);
	}

	/**
	 * AES-128-CBC 解密
	 * @param content 密文
	 * @param IV 偏移向量IV
	 * @param KEY key
	 * @return 解密后的字符串
	 * @throws Exception 异常
	 */
	public String decrypt(String content,String IV,String KEY) throws Exception {
		byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
		byte[] encrypted1 = Base64.getDecoder().decode(content);
		byte[] original = cipher.doFinal(encrypted1);
		return new String(original);
	}

}